package com.syyo.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syyo.common.constant.ProductContant;
import com.syyo.common.enums.ResultEnum;
import com.syyo.common.exception.SysException;
import com.syyo.gulimall.product.domain.entity.*;
import com.syyo.gulimall.product.domain.req.AttrReq;
import com.syyo.gulimall.product.domain.req.AttrSpuReq;
import com.syyo.gulimall.product.domain.resp.AttrResp;
import com.syyo.gulimall.product.mapper.*;
import com.syyo.gulimall.product.service.AttrService;
import com.syyo.gulimall.product.service.ProductAttrValueService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 商品属性
 *
 * @author syyo
 * @email syyo@gmail.com
 * @date 2021-01-20 09:32:12
 */
@Service
public class AttrServiceImpl extends ServiceImpl<AttrMapper, AttrEntity> implements AttrService {

    @Autowired
    private AttrMapper attrMapper;

    @Autowired
    private AttrAttrgroupRelationMapper attrAttrgroupRelationMapper;

    @Autowired
    private AttrGroupMapper attrGroupMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductAttrValueMapper productAttrValueMapper;

    @Autowired
    private ProductAttrValueService productAttrValueService;


    /**
     * 新增
     */
    @Override
    @Transactional
    public int add(AttrReq req) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(req, attr);
        // 添加创建时间和更新时间
        int insert = attrMapper.insert(attr);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10001.getCode(), ResultEnum.E_10001.getMessage());
        }
        if (req.getAttrType() == ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode() && req.getAttrGroupId() != null) {
            // 基本属性才修改分组的关联关系
            // 添加分组
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(req.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrSort(1);
            attrAttrgroupRelationMapper.insert(attrAttrgroupRelationEntity);
        }

        return insert;
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public int del(Integer id) {
        int insert = attrMapper.deleteById(id);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10002.getCode(), ResultEnum.E_10002.getMessage());
        }
        return insert;
    }

    /**
     * 编辑
     */
    @Override
    @Transactional
    public int edit(AttrReq req) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(req, attr);
        int insert = attrMapper.updateById(attr);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10003.getCode(), ResultEnum.E_10003.getMessage());
        }
        if (req.getAttrType().equals(ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            // 基本属性才修改分组的关联关系
            // 修改分组关联
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(req.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(req.getAttrId());
            Integer count = attrAttrgroupRelationMapper.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", req.getAttrId()));
            if (count > 0) {
                // 大于0修改
                attrAttrgroupRelationMapper.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", req.getAttrId()));
            } else {
                // 新增
                attrAttrgroupRelationMapper.insert(attrAttrgroupRelationEntity);
            }
        }
        return insert;
    }

    /**
     * 详情
     */
    @Override
    public AttrResp findOne(Integer id) {
        AttrResp attrResp = new AttrResp();
        AttrEntity attr = attrMapper.selectById(id);
        BeanUtils.copyProperties(attr, attrResp);

        if (ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode().equals(attr.getAttrType())) {
            // 查询分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", id));
            if (attrAttrgroupRelationEntity != null) {
                attrResp.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupMapper.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrResp.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 查询分类信息
        Long catelogId = attr.getCatelogId();
        List<Long> catelogIds = new ArrayList<>();
        recursionFindCategoryId(catelogId, catelogIds);
        Collections.reverse(catelogIds);  //实现List集合逆序排列
        attrResp.setCatelogIds(catelogIds);
        CategoryEntity categoryEntity = categoryMapper.selectById(catelogId);
        if (categoryEntity != null) {
            attrResp.setCatelogName(categoryEntity.getName());
        }
        return attrResp;
    }

    /**
     * 递归查询分类id
     */
    private List<Long> recursionFindCategoryId(Long catelogId, List<Long> catelogIds) {
        catelogIds.add(catelogId);
        CategoryEntity categoryEntity = categoryMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            recursionFindCategoryId(categoryEntity.getParentCid(), catelogIds);
        }
        return catelogIds;
    }

    /**
     * 列表
     */
    @Override
    public Page<AttrResp> findPage(Integer pageNum, Integer pageSize, AttrReq req, String attrType) {

        Page<AttrEntity> teacherPage = new Page<AttrEntity>(pageNum, pageSize);
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equals(attrType) ? ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductContant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (req.getCatelogId() != 0) {
            wrapper.eq("catelog_id", req.getCatelogId());
        }
        IPage<AttrEntity> list = attrMapper.selectPage(teacherPage, wrapper);

        // 流式处理，
        List<AttrEntity> records = list.getRecords();
        List<AttrResp> attrResps = records.stream().map(attrEntity -> {
            AttrResp attrResp = new AttrResp();
            BeanUtils.copyProperties(attrEntity, attrResp);

            // 查询分组名称
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupMapper.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                attrResp.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            }

            // 查询分组名称
            CategoryEntity categoryEntity = categoryMapper.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResp.setCatelogName(categoryEntity.getName());
            }
            return attrResp;
        }).collect(Collectors.toList());
        Page<AttrResp> attrRespPage = new Page<>();
        attrRespPage.setRecords(attrResps);
        attrRespPage.setCurrent(list.getCurrent());
        attrRespPage.setPages(list.getPages());
        attrRespPage.setSize(list.getSize());
        attrRespPage.setTotal(list.getTotal());
        return attrRespPage;
    }


    @Override
    public List<ProductAttrValueEntity> findAttr(Integer spuId) {
        return productAttrValueMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }

    @Transactional
    @Override
    public int editSpuAttr(Long spuId, List<AttrSpuReq> req) {
        // 删除spu之前关联的属性
        productAttrValueMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<ProductAttrValueEntity> collect = req.stream().map(item -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(item, entity);
            entity.setSpuId(spuId);
            return entity;
        }).collect(Collectors.toList());
        boolean b = productAttrValueService.saveBatch(collect);
        return 1;
    }

}